# -*-coding:utf8-*-
import sys
reload(sys)  
sys.setdefaultencoding('utf8')

import requests
from lxml import etree

import os
import datetime
import traceback
import win32clipboard as w
import win32con

config_content_1 = """#配置要获取的指数在html中对应的行的号码
40820
179
169
178
37426"""

if os.path.exists(r'config1.conf'):
    pass
else:
    with open(r'config1.conf', 'w') as fout:
        fout.write(config_content_1)
        fout.flush()
        fout.close()

class Config1(object):
    def __init__(self):
        self.index_numbers = []
        lines = []
        with open(r'config1.conf', 'r') as f:
            lines = f.readlines()
        for x in xrange(0, len(lines)):
            if lines[x][0] == '#' or len(lines[x].strip()) == 0:
                pass
            else:
                try:
                    self.index_numbers.append(str(int(lines[x].strip())))
                except Exception, e:
                    traceback.print_exc()
                else:
                    pass
                finally:
                    pass
    def get_index_numbers(self):
        if len(self.index_numbers) == 0:
            raise Exception("同目录下找不到config.conf文件")
            sys.exit(1)
        return self.index_numbers

class Message(object):

    word_dict = {
        "01": "跌幅",
        "02": "涨幅",
        "03": "下跌",
        "04": "上涨",
    }


    def __init__(self, index_name, last_price, highest_price, lowest_price, net_change, change_percent, time_date):
        self.index_name = index_name
        self.last_price = last_price
        self.highest_price = highest_price
        self.lowest_price = lowest_price
        self.net_change = net_change
        self.change_percent = change_percent
        self.date = datetime.datetime.strptime(time_date, "%d/%m/%Y")

    def to_string(self):
        return self.index_name+str(self.date.strftime('%m月%d日'))+self.word_dict[self.rise_down(self.net_change)]+self.net_change[1:]+"，"+self.word_dict[self.rise_down(self.change_percent)]+self.change_percent[1:]+"，收盘"+self.last_price.replace(",", "")+"。"

    def rise_down(self, string):
        ret_code = "00"
        if string[-1] == "%":
            if string[0] == "-":
                ret_code = "01"
            else:
                ret_code = "02"
        else: 
            if string[0] == "-":
                ret_code = "03"
            else:
                ret_code = "04"
        return ret_code


if __name__ == '__main__':
    config1 = Config1()
    index_numbers = config1.get_index_numbers()

    url="https://cn.investing.com/indices/major-indices"
    page=requests.get(url)
    html=page.text
    selector = etree.HTML(html)

    '''
    保存所有的信息到列表中
    '''
    messages = []

    for number in index_numbers:
        try:
            index_name = selector.xpath('//tr[@id="pair_'+number+'"]/td[@class="bold left noWrap elp plusIconTd"]/a/text()')[0]
            last_price = selector.xpath('//tr[@id="pair_'+number+'"]/td[@class="pid-'+number+'-last"]/text()')[0]
            highest_price = selector.xpath('//tr[@id="pair_'+number+'"]/td[@class="pid-'+number+'-high"]/text()')[0]
            lowest_price = selector.xpath('//tr[@id="pair_'+number+'"]/td[@class="pid-'+number+'-low"]/text()')[0]
            net_change = selector.xpath('//tr[@id="pair_'+number+'"]/td[contains(@class, "pid-'+number+'-pc")]/text()')[0]
            change_percent = selector.xpath('//tr[@id="pair_'+number+'"]/td[contains(@class, "pid-'+number+'-pcp")]/text()')[0]
            time_date = selector.xpath('//tr[@id="pair_'+number+'"]/td[@class=" pid-'+number+'-time"]/text()')[0] + "/" + datetime.datetime.now().strftime('%Y')
        except Exception, e:
            print number
            traceback.print_exc()
            continue
        else:
            pass
        finally:
            pass

        # print index_name
        # print last_price
        # print highest_price
        # print lowest_price
        # print net_change
        # print change_percent
        # print time_date

        '''
        组合成所需的消息
        '''
        message = Message(index_name, last_price, highest_price, lowest_price, net_change, change_percent, time_date)
        messages.append(message)

    '''
    用于写入剪贴板的信息
    '''
    text = ''
    for message in messages:
        text += (message.to_string() + "\n")

    '''
    信息写入剪贴板中
    '''
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(win32con.CF_UNICODETEXT, text)
    w.CloseClipboard()

    '''
    尝试从剪贴板读取信息
    '''
    w.OpenClipboard()
    print w.GetClipboardData(w.CF_UNICODETEXT)
